<template>
    <el-dialog title="新增用户" @close="closeUser" :visible.sync="isShow" width="900px" @open="openCreate"
      :close-on-click-modal="false" center>
      <div v-loading="loading">
        <div class="content">
          <el-card>
            <el-form size="mini" ref="newUserDate" :model="newUserDate" :rules="rules"  label-width="100px"
              label-position="left">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="userNum" label="用户编号:">
                    <el-input v-model="newUserDate.userNum" placeholder="请输入用户编号（请输入工号）" @blur="userNumCheck()"></el-input>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item prop="tellerNo" label="柜员号:">
                    <el-input v-model="newUserDate.tellerNo" placeholder="请输入柜员号"></el-input>
                  </el-form-item>
                </el-col> -->
              <!-- </el-row> -->
              <!-- <el-row :gutter="30"> -->
                <el-col :span="12">
                  <el-form-item prop="branchId" label="所属机构:">
                    <el-select v-model="newUserDate.branchId" filterable>
                      <el-option v-for="item in brnoList" :key="item.value" :label="item.cname" :value="item.orgno"
                        :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="userName" label="用户名称:">
                    <el-input v-model="newUserDate.userName" placeholder="请输入用户名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="engName" label="英文名称:">
                    <el-input v-model="newUserDate.engName" placeholder="请输入英文名称"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="sex" label="性别:">
                    <el-select v-model="newUserDate.sex">
                      <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value"
                        :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="emailAddress" label="邮箱:">
                    <el-input v-model="newUserDate.emailAddress" placeholder="请输入邮箱"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="certType" label="证件类型:">
                    <el-select v-model="newUserDate.certType">
                      <el-option v-for="item in certTypeList"  :key="item.DataKeyVal"
                    :label="item.DataKeyVal+'-'+item.Meaning"
                    :value="item.DataKeyVal"
                    :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="certNum" label="证件号码:">
                    <el-input v-model="newUserDate.certNum" placeholder="请输入证件号码"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="telephone" label="手机号:">
                    <el-input v-model="newUserDate.telephone" placeholder="请输入手机号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="contactNum" label="联系电话:">
                    <el-input v-model="newUserDate.contactNum" placeholder="请输入联系电话"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item prop="contactAddr" label="联系地址:">
                    <el-input v-model="newUserDate.contactAddr" placeholder="请输入联系地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="userLevel" label="用户级别:">
                    <el-select v-model="newUserDate.userLevel">
                      <el-option v-for="item in userLevelList"  :key="item.DataKeyVal"
                    :label="item.DataKeyVal+'-'+item.Meaning"
                    :value="item.DataKeyVal"
                    :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="生效日期" prop="startdate">
                    <el-date-picker v-model="newUserDate.startdate" :editable=false value-format="yyyyMMdd" type="date"
                      placeholder="选择生效日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="失效日期" prop="enddate">
                    <el-date-picker v-model="newUserDate.enddate" :editable=false value-format="yyyyMMdd" type="date"
                      placeholder="选择失效日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
                <!-- <el-row :gutter="30">
                  <el-col :span="12">
                  <el-form-item prop="certtp" label="认证方式（统一登录平台）">
                    <el-select v-model="newUserDate.certtp">
                      <el-option v-for="item in certtpList" :key="item.value" :label="item.label" :value="item.value"
                        :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                  <!-- <el-col :span='24'>
              <el-form-item label="用户类型" prop="usertype">
                <el-radio-group v-model="newUserDate.usertype">
                  <el-radio :label=true>V端用户</el-radio>
                  <el-radio :label=false>C端用户</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
                <!-- </el-row> -->
            </el-form>
          </el-card>
          <div style="text-align:right;margin:20px 0">
             <el-button size="mini" @click="addType">取消</el-button> 
            <el-button type="primary" size="mini" @click="addUser">确认</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
</template>
<script>
import selectTree from "@/components/selectTree2/";
import request from "@/common/utils/request";
import createUser from "@/message/userManage/user/user-create";
import branchList from "@/message/shared/branch-list";
import selectLoad from "@/message/shared/dict-select-load";
import toolBox from "@/common/utils/toolBox";
import InquireUser from "@/message/userManage/user/inquire-user";


export default {
  name: "create-user",
  data() {
    let validatorPhone = (rule, value, callback) => {
      //校验手机号
      if (value != "") {
        let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号"));
        }
      } else {
        callback();
      }
    };
    let validatorEmail = (rule, value, callback) => {
      //校验邮箱
      if (value != "" ) {
        let reg = new RegExp(
          "^[a-zA-Z0-9]+([._\\-]*[a-zA-Z0-9])*@([a-zA-Z0-9]+[-a-zA-Z0-9]*[a-zA-Z0-9]+.){1,63}[a-zA-Z0-9]+$"
        );
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱"));
        }
      } else {
        callback();
      }
    };
    let certNumCheck = (rule, value, callback) => {
      //校验身份证号码
      if (value != "" && (this.newUserDate.certType=="10101" || this.newUserDate.certType=="10102") ){
        let reg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的身份证号"));
        }
      } else {
        callback();
      }
    };
    let startdateCheck = (rule, value, callback) => { //自定义表单验证 校验IP地址
        if (value != "") {
          let time = toolBox.getNowTime(0);
          if (value - time >= 0) {
            callback();
          } else {
            callback(new Error("生效日期必须大于当前日期"));
          }
        } else {
          callback();
        }
      };
      let enddateCheck = (rule, value, callback) => { //自定义表单验证 校验IP地址
        if (value != "") {
          if (value - this.newUserDate.startdate >= 0) {
            callback();
          } else {
            callback(new Error("失效日期必须大于生效日期"));
          }
        } else {
          callback();
        }
      };

    return {
      loading: false,
      brnoList: [],
      sexList: [
        {
          label: "男",
          value: "0"
        },
        {
          label: "女",
          value: "1"
        }
      ],
      certtpList: [
        {
          label: "密码",
          value: "0"
        },
        {
          label: "指纹",
          value: "2"
        }
      ],
      certTypeList: [],
      userLevelList: [],
      newUserDate: {
        certtp:"0",
        //表单信息
        userNum: "",
        userName: "",
        engName: "",
        branchId: "",
        sex: "0",
        certType: "10101",
        certNum: "",
        tellerNo: "",
        contactNum: "",
        contactAddr: "",
        telephone: "",
        emailAddress: "",
        userLevel: "",
        startdate: "",
        enddate: "",
        // usertype:true
      },
      rules: {
        //校验对象
        // userID: [
        //   { required: true, message: "请输入用户编号", trigger: "blur" }
        // ],
        branchId: [
          {
            required: true,
            message: "请选择机构号",
            trigger: "change"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "blur"
          },
          {
            max: 200,
            message: "用户名称长度少于200个字符",
            trigger: "blur"
          }
        ],
        // remark: [{ max:10, message: "请输入少于120位字符", trigger: "blur" }],
        telephone: [
          {
            message: "手机号长度少于20个字符",
            max: 20,
            trigger: "blur"
          },
          {
            require: false,
            validator: validatorPhone,
            trigger: "blur"
          }
        ],
        emailAddress: [
          {
            max: 20,
            message: "邮箱长度少于20个字符",
            trigger: "blur"
          },
          {
            require: false,
            validator: validatorEmail,
            trigger: "blur"
          }
        ],
        certNum:[{
            require: false,
            validator: certNumCheck,
            trigger: "blur"
          }],
        userNum: [
          {
            required: true,
            message: "请输入用户编号",
            trigger: "blur"
          },
          {
            max: 10,
            message: "请输入正确工号，长度少于10个字符",
            trigger: "blur"
          }
        ],
        userLevel: [
          {
            required: true,
            message: "请选择用户级别",
            trigger: "change"
          }
        ],
        startdate: [
          {
            required: true,
            message: "请选择生效日期",
            trigger: "change"
          },
          {
              validator: startdateCheck,
              trigger: 'blur'
            }
        ],
        enddate: [
          {
            required: true,
            message: "请选择失效日期",
            trigger: "change"
          },
          {
              validator: enddateCheck,
              trigger: 'blur'
            }
        ],
        tellerNo: [
          {
            required: true,
            message: "请输入柜员号",
            trigger: "blur"
          },
          {
            max: 20,
            message: "请输入正确柜员号，长度少于20个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  props: {
    //父元素传递的数据
    option: Object
  },
  components: {
    selectTree
  },
  computed: {
    isShow: {
      //创建用户弹窗是否显示
      get: function() {
        return this.option.isShow;
      },
      set: function(newValue) {
        this.option.isShow = newValue;
      }
    }
  },

  methods: {
     addType() { //关闭弹窗事件，清楚表单验证
        this.option.isShow = false;
        this.$refs["newUserDate"].resetFields(); //清除表单验证
      },
    initList() {
      //初始化下拉列表
      let resBody = new branchList();
      resBody.data.orgno = this.$store.getters.BranchNum;
      request(resBody)
        .then(response => {
          this.loading = false;
          this.brnoList = response.RspInfo.Result;
        })
        .catch(error => {
          this.loading = false;
          console.error("错误信息", error);
        });
    },
    loadCertTypeList() {
      let resBody = new selectLoad();
      resBody.data.DataKey = "CtfTp";
      request(resBody)
        .then(response => {
          this.certTypeList = response.RspInfo.Result;
        })
        .catch(error => {
          this.loading = false;
          console.error("错误信息", error);
        });
    },
    userNumCheck(){
      if(this.newUserDate.userNum == ""){
        return false
      }
      this.loading = true;
      let resBody = new InquireUser();
      resBody.data.Tlr = this.newUserDate.userNum;
      resBody.data.StartRows = "0";
      resBody.data.PageSize = "1";
      resBody.data.CurtPage = "1";
      request(resBody)
        .then(response => {
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.newUserDate.userNum = ""
            this.$message({
              type: "warning",
              message: "用户号已存在!"
            })
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    },
    loadUserLevelList() {
      let resBody = new selectLoad();
      resBody.data.DataKey = "TlrLevel";
      request(resBody)
        .then(response => {
          this.userLevelList = response.RspInfo.Result;
        })
        .catch(error => {
          this.loading = false;
          console.error("错误信息", error);
        });
    },
    openCreate() {
      //打开弹窗事件
      this.loading = true;
      this.initList();
      this.loadCertTypeList();
      this.loadUserLevelList();
      if (this.$refs.newUserDate) {
        this.$refs["newUserDate"].clearValidate(); //清楚表单验证
        this.$refs["newUserDate"].resetFields(); //清除表单验证
      }
      this.loading = false;
    },
    closeUser() {
      //关闭弹窗清楚表单数据并清楚表单验证
      if (this.$refs["newUserDate"] != undefined) {
        this.$refs["newUserDate"].resetFields(); //清楚表单验证
        this.$refs["newUserDate"].clearValidate(); //清楚表单验证
      }
      this.$emit("refreshTable");
    },
    addUser() {
      //添加用户
      this.$refs["newUserDate"].validate(valid => {
        if (valid) {
          this.loading = true;
          let resBody = new createUser();
          resBody.data.UserNum = this.newUserDate.userNum;
          resBody.data.UserName = this.newUserDate.userName;
          resBody.data.BranchNum = this.newUserDate.branchId;
          resBody.data.EngName = this.newUserDate.engName;
          resBody.data.EnableDate = this.newUserDate.startdate;
          resBody.data.TermDate = this.newUserDate.enddate;
          resBody.data.CertType = this.newUserDate.certType;
          resBody.data.CertNum = this.newUserDate.certNum;
          resBody.data.Gender = this.newUserDate.sex;
          resBody.data.ContactNum = this.newUserDate.contactNum;
          resBody.data.PhoneNum = this.newUserDate.telephone;
          resBody.data.ContactAddr = this.newUserDate.contactAddr;
          resBody.data.Mailbox = this.newUserDate.emailAddress;
          resBody.data.CertType = this.newUserDate.certType;
          resBody.data.UserLevel = this.newUserDate.userLevel;
          resBody.data.CreaUser = this.$store.getters.UserNum;
          resBody.data.CreaDate = toolBox.getNowTime(0);
          resBody.data.CashierCardNum = this.newUserDate.tellerNo;
          resBody.data.certtp = this.newUserDate.certtp;
          request(resBody)
            .then(response => {
              if (response.SYS_HEAD.ReturnCode === "000000") {
                this.loading = false;
                this.isShow = false;
                this.$message({
                  type: "success",
                  message: "用户创建成功!"
                }).catch(() => {
                  
                });
                this.addType();
              } else {
                this.$message({
                  type: "warning",
                  message: "用户创建失败!" + response.SYS_HEAD.ReturnMessage
                });
                this.loading = false;
              }
              // debugger
              // this.$refs["newUserDate"].resetFields(); //清除表单验证
              // this.$refs["newUserDate"].clearValidate(); //清楚表单验证
              // this.isShow = false;
              
            })
            .catch(error => {
              this.loading = false;
            });
        } else {
          this.$message({
            type: "warning",
            message: "请输入合法的数据！"
          });
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
}

// .footer {
//   width: 100%;

//   margin-top: 10px;
// }
.require {
  color: red;
}

.dialog-text {
  display: inline-block;
  width: 100%;
  text-align: center;
  color: red;
  font-size: 18px;
}

.role {
  width: 95%;
  border: 1px solid #eee;
  border-radius: 4px;
  height: 290px;

  .roleHeader {
    color: #606266;
    font-weight: 500;
    font-size: 14px;
    background: #f5f7fa;
    height: 42px;
    box-sizing: border-box;
    padding: 9px;
    overflow-y: auto;
  }
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%
}
.el-card {
  overflow: inherit;
}
</style>
